﻿using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static Proxy.Utility;

namespace Proxy
{
    public class Auto_InfeedScanner
    {
        private Socket socket;
        private InsertInfoHandle Handle_Insert;
        private SearchInfoHandle Handle_Search;
        private HomagChina.Basic.CCT.Tools.SocketHelper socketHelper;

        public Auto_InfeedScanner(string Ip, int Port)
        {
            Handle_Insert = new InsertInfoHandle();
            Handle_Search = new SearchInfoHandle();
            //连接Scanner
            socketHelper = new HomagChina.Basic.CCT.Tools.SocketHelper();
            socket = socketHelper.Connect(Ip, Port);
            Task.Factory.StartNew(() => { MonitorDataReceive(socket, Ip, Port); });
        }

        public void MonitorDataReceive(Socket socket, string Ip, int Port)
        {
            byte[] bytes = new byte[1024];
        Start:
            while (true)
            {
                try
                {
                    Thread.Sleep(1000);
                    if (socket == null || !socket.Connected)
                    {
                        socket = socketHelper.Connect(Ip, Port);
                    }
                    if (!Globle.isInfeedActive)
                    {
                        goto Start;
                    }
                    int bytesRec = socket.Receive(bytes);
                    if (bytesRec > 0)
                    {
                        if (Globle.isRunEmptyActive)
                        {
                            HomagGroup.Base.UI.Windows.MessageBox.Show(GetLocalText("Run Empty function is running  loading function is disabled"));
                            goto Start;
                        }
                        //收到的消息
                        string Msg = Encoding.UTF8.GetString(bytes, 0, bytesRec).ToString().Replace('\u0002', ' ').Replace('\\', ' ').Trim();
                        if (string.IsNullOrWhiteSpace(Msg))
                        {
                            goto Start;
                        }
                    }
                    goto Start;
                }
                catch (Exception ex)
                {
                    socket.Dispose();
                    SerilogHandle.Logger_AutoScanner.Error(ex.Message);
                    goto Start;
                }
            }
        }
    }
}